import cv2

# 滑动条回调函数
def nothing(x):
    pass

# 打开摄像头
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)

# 创建窗口
cv2.namedWindow('camera')
# 创建滑动条
cv2.createTrackbar('threshold', 'camera', 0, 255, nothing)

while camera.isOpened():
    # 从摄像头获取图像
    image = camera.read()[1]
    # 转为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 模糊细节
    blur = cv2.blur(gray, (5, 5))
    # 获取滑动条位置
    threshold = cv2.getTrackbarPos('threshold','camera')
    # 二值化
    binary = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)[1]
    # 查找轮廓
    contours = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
    if len(contours):
        # 获取面积最大的轮廓
        c = max(contours, key=cv2.contourArea)
        # 计算轮廓矩
        m = cv2.moments(c)
        # 计算轮廓中心
        cx = int(m["m10"] / m["m00"])
        cy = int(m["m01"] / m["m00"])
        # 绘制轮廓
        cv2.drawContours(image, c, -1, (0, 0, 255), 2)
        # 绘制中心
        cv2.circle(image, (cx, cy), 5, (0, 0, 255), 2)
        
        # 显示中心坐标
        text = "%.2f, %.2f"%(cx, cy)
        cv2.putText(image, text, (5,50 ), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
        
    cv2.imshow("camera", image)
    if cv2.waitKey(1) == 27:
        break
    
cv2.destroyAllWindows()
camera.release()
